package com.everfro.codeshare.dialog;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Properties;

import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.wizard.IWizard;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.IWorkbenchPage;

import com.everfro.codeshare.Activator;
import com.everfro.codeshare.preferences.PreferenceConstants;
import com.everfro.codeshare.views.ViewContentProvider;
import com.everfro.codeshare.views.codeShareHistory;

public class SendToCodeShareWizard extends Wizard implements IWizard {
	
	public String textToSend;
	private SendDialogPage page1;
	
	public SendToCodeShareWizard(String codeText){
		super();
		needsProgressMonitor();
		this.textToSend = codeText;
		setWindowTitle("Send to codeShare");
		setDefaultPageImageDescriptor(Activator.getImageDescriptor("/icons/codeShare_header.gif"));
		
		
	}
	public void addPages() {
		page1 = new SendDialogPage("Send to codeShare", this.textToSend);
		addPage(page1);
	
	
	}

	public boolean performFinish() {
		
		String returnString = doSubmit(page1.codeToSend.getText(),page1.expiresCombo.getText(), page1.comments.getText());
		
		if(returnString != null){
			//the post has gone through, now parse it:
			System.out.println("full return: "  + returnString);
			String status = "1";
			String message = "";
			String url = "";
			
			//Parse the returning info
				String[] retMessages = returnString.split("\\|");
				status = retMessages[0];
				url = retMessages[2];
				message = retMessages[1] + "\ncodeShare url:" + url;
				
				
				if("0".equals(status)){
					saveHistory(url, page1.expiresCombo.getText(), page1.comments.getText());
					
					//Dialog doneDialog = new Dialog(getShell());
					ResultDialog results = new ResultDialog(getShell(),message, url);
					
					
					results.open();
					/*
					MessageDialog.openInformation(
							getShell(),
							"codeShare: Information sent",
							message);
				*/
				//Get the viewer and refresh it 
					IWorkbenchPage activePage = Activator.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage();
					
					IViewReference[] viewReferences = activePage.getViewReferences();

					for (int i = 0; i < viewReferences.length; i++) {
						 IViewPart part = viewReferences[i].getView(false);
						 
						 if(part instanceof codeShareHistory){
							 codeShareHistory view = (codeShareHistory)part;
							 view.getViewer().setContentProvider(new ViewContentProvider());
							 	
						 }
					}
					
				}
				else{
					MessageDialog.openError(getShell(), "codeShare: Error", message);
				}
				
			
			return true;
		}
		else{
			page1.setErrorMessage("There was an error sending the message to codeShare. Check your username, password and the codeShare URL");
		}
		return false;
	}
	
	
	/**
	 * This function actually saves a file in the snippet history, the file will be datestamped and will contain the url + 
	 * The expiration + date sent
	 * 
	 * Could be a properties file
	 */
	private void saveHistory(String url, String expiration, String comment){

		
		
		String historyPath = Activator.getDefault().getStateLocation().toOSString()+"/history";
		
		//Create the date function 
		Date nowish = new Date(System.currentTimeMillis());
		SimpleDateFormat submitedFormat;
		submitedFormat = new SimpleDateFormat("yyyy-MM-dd");
		
		
		
		Properties historyFile = new Properties();
		historyFile.setProperty("url", url);
		historyFile.setProperty("expires", dateConverter(expiration));
		historyFile.setProperty("submitted", submitedFormat.format(nowish));
		if(comment.length() == 0){
			comment = "";
		}
		historyFile.setProperty("comment", comment);
		
		
		try {
			SimpleDateFormat df;
			df = new SimpleDateFormat("yyyyMMddHmmss");
			
			FileOutputStream out = new FileOutputStream(historyPath + "/" + df.format(nowish) + ".txt");
			historyFile.save(out, "codeShare history file");
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	private String dateConverter(String expiration) {
		// This parses a date and sets the date in the file in a format that we know to
		// know when it expires, this means that whenever we do a refresh, we can remove expired items
		String[] strings = expiration.split(" ");
		int periodQty = Integer.parseInt(strings[0]);
		String periodType = strings[1].substring(0, 1);
		
		int daysToAdd = periodQty;
		
		if(periodType.equalsIgnoreCase("w")){
			daysToAdd = daysToAdd * 7;
		}
		String DATE_FORMAT = "yyyy-MM-dd";		//Refer Java DOCS for formats
		java.text.SimpleDateFormat sdf =  new java.text.SimpleDateFormat(DATE_FORMAT);
		Calendar c1 = Calendar.getInstance();
		c1.add(Calendar.DATE,daysToAdd);
		
		String expiresDate = sdf.format(c1.getTime());
		return expiresDate;
	}
	private String doSubmit(String code, String expires, String comments ){
		
	    try{
		URL                 url;
	    URLConnection   urlConn;
	    DataOutputStream    printout;
	    DataInputStream     input;
	    // URL of CGI-Bin script.
	    IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
	    //Refactor this so it loads from the ini file
	   
	    
	    String codeShareURL = "http://codeshare.everfro.com/input/";
	 
	    
	    String codeShareUsername = preferenceStore.getString(PreferenceConstants.P_USERNAME);
	    String codeSharePassword = preferenceStore.getString(PreferenceConstants.P_PASSWORD); 
	    url = new URL (codeShareURL);
	    // URL connection channel.
	    urlConn = url.openConnection();
	    // Let the run-time system (RTS) know that we want input.
	    urlConn.setDoInput (true);
	    // Let the RTS know that we want to do output.
	    urlConn.setDoOutput (true);
	    // No caching, we want the real thing.
	    urlConn.setUseCaches (false);
	    // Specify the content type.
	    urlConn.setRequestProperty
	    ("Content-Type", "application/x-www-form-urlencoded");
	    // Send POST output.
	    printout = new DataOutputStream (urlConn.getOutputStream ());
	    String content =
	    "code=" + URLEncoder.encode (code) +
	    "&expires=" + URLEncoder.encode (expires) + 
	    "&comments=" + URLEncoder.encode(comments)+ 
	    "&serviceID=660258BD-A275-DEBB-F6EBF1D6A7AABF40" + 
	    "&username=" + URLEncoder.encode(codeShareUsername)+ 
	    "&password="+ URLEncoder.encode(codeSharePassword);
	    printout.writeBytes (content);
	    printout.flush ();
	    printout.close ();
	    // Get response data.
	    input = new DataInputStream (urlConn.getInputStream ());
	    String str;
	    while (null != ((str = input.readLine())))
	    {
	    	if(str.trim().length()>0) return str.trim();
	    }
	    
	    
	    input.close ();
	    }
	    catch(Exception exception){
	    	System.err.println(exception);
	    	return null;
	    }
		return null;
	    

		
	}
	public String getTextToSend() {
		return textToSend;
	}
	public void setTextToSend(String textToSend) {
		this.textToSend = textToSend;
	}

}
